package com.kingcat.smartchair;

import android.Manifest;
import android.app.*;
import android.content.*;

import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.os.*;

import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;

import android.webkit.*;

import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.*;

import com.kingcat.smartchair.utils.AppUtils;
import com.kingcat.smartchair.utils.DeviceUt;
import com.kingcat.smartchair.utils.Tools;
import com.kingcat.smartchair.view.CommonProgressDialog;

import java.io.*;
import java.net.*;

import com.kingcat.smartchair.webview.*;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.*;


public class MainActivity extends Activity {

    private static final int INSTALL_REQUEST_CODE = 123;

    private SmartChairWebView mWebView;

    private static final String TAG = "MainActivity";

    // 下载存储的文件名
    private static final String DOWNLOAD_NAME = "smartchair.apk";

    private NetworkChangedReceiver networkChangeReceiver;


    //  麦克风权限
    private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 101;

    private IntentFilter intentfilter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化
        AppUtils.init(getApplicationContext());

        //Intent i = new Intent(MainActivity.this , TestActivity.class);
        //startActivity(i);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        getWindow().setAttributes(params);

        // 设置横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 隐藏虚拟按键，并且全屏
        hideBottomUIMenu();

        //  设置视图
        setContentView(R.layout.activity_main);

        // 网络状态管理
        IntentFilter intentNetChangeFilter = new IntentFilter();
        intentNetChangeFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//为过滤器添加 广播过滤
        networkChangeReceiver = new NetworkChangedReceiver();
        registerReceiver(networkChangeReceiver, intentNetChangeFilter);

        // 注册一个定时服务
        Intent intentService = new Intent(this, SmartChairService.class);
        startService(intentService);

        // 浏览器内容加载
        mWebView = (SmartChairWebView) findViewById(R.id.webview);

        // 设置WEBVIEW属性
        mWebView.setAttr(MainActivity.this);

        AppUtils.setAppWebView(mWebView);
    }

    @Override
    public void onDestroy() {

        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        unregisterReceiver(networkChangeReceiver);
        super.onDestroy();
    }

    // 隐藏虚拟按键，并且全屏
    protected void hideBottomUIMenu(){

        //隐藏虚拟按键，并且全屏
        if(Build.VERSION.SDK_INT >11&& Build.VERSION.SDK_INT <19) {// lower api

            View v =this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);

        }else if(Build.VERSION.SDK_INT >=19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
       }
    }

    // 返回键的处理
    @Override
    public void onBackPressed() {
        // 设备号
        //String udid = DeviceUt.GetUDID(AppUtils.getAppContext());
        //sn = "ac001415c3c0c6a204e";
        //mWebView.loadUrl("file:///android_asset/index.html?udid=" + udid);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    // 更新升级的方法（手动下载调用）
    public void Update(){

        // 重置大小
        AppUtils.setApkSize(0);
        AppUtils.setApkDownloadSize(0);

        Log.d("*********************************************", "update begin!");

        // 检测版本号
        String res = "";
        if(AppUtils.getAppContext().getString(R.string.app_env).equals("prod"))
        {
            //res = Tools.doGET(AppUtils.getAppContext().getString(R.string.smartchari_apkupdateurl_prod));
        }

        if(AppUtils.getAppContext().getString(R.string.app_env).equals("dev"))
        {
            //res = Tools.doGET(AppUtils.getAppContext().getString(R.string.smartchari_apkupdateurl_dev));
        }

        JSONObject jsonObject = JSON.parseObject(res);
        String url = jsonObject.getString("DownloadUrl") ;

        download(url);
    }

    protected String download(String Url) {

        Log.d("*********************************************",  " 准备下载：" + Url );

        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        File file = null;
        try {
            URL url = new URL(Url);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            // expect HTTP 200 OK, so we don't mistakenly save error
            // report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP "
                        + connection.getResponseCode() + " "
                        + connection.getResponseMessage();
            }
            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // 设置大小
            AppUtils.setApkSize(fileLength);
            Log.d("*********************************************",  " 文件大小：" + String.valueOf(fileLength) );

            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                String apkPath = this.getExternalCacheDir().getPath()+ File.separator + "app" + File.separator;
                file = new File(apkPath, "smartchair.apk");

                if (!file.exists()) {
                    // 判断父文件夹是否存在
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                }
            } else {
                Toast.makeText(this, "sd卡未挂载",
                        Toast.LENGTH_LONG).show();
            }

            // 讲下载的文件流写到本地
            input = connection.getInputStream();
            output = new FileOutputStream(file);
            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);

                AppUtils.setApkDownloadSize(total);
                Log.d("*********************************************",  " 已下载：" + String.valueOf(total) );
            }

            //调用安装;
            callInstall();
        } catch (Exception e) {
            //System.out.println("err:" + e.toString());
            Log.d("*********************************************",  " 下载异常：" + e.toString());
            return e.toString();

        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

    // 呼出安装权限设置
    private  void callInstall(){
        //installApk();

         // 请求安装权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (!getPackageManager().canRequestPackageInstalls()) {
                // 引导用户授予安装未知来源应用的权限
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, INSTALL_REQUEST_CODE);
            } else {
                // 已有权限，执行安装操作
                installApk();
            }
        } else {
            // Android 版本低于 O，无需权限请求，直接执行安装操作
            installApk();
        }
    }

    // 权限申请结束后的回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INSTALL_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // 用户已授予安装未知来源应用的权限，执行安装操作
                installApk();
            } else {
                // 用户未授予权限，可以进行相应的处理
                Toast.makeText(this, "未授予权限，无法安装应用", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 安装方法
    private void installApk()
    {
        // 替换以下路径为实际 APK 文件的路径
        String apkFilePath = this.getExternalCacheDir().getPath()+ File.separator + "app" + File.separator + "smartchair.apk";

        // 创建 Intent
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // Android 7.0 及以上版本使用 FileProvider
            uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", new File(apkFilePath));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            // Android 7.0 以下版本直接使用 Uri.fromFile
            uri = Uri.fromFile(new File(apkFilePath));
        }

        // 设置 Intent 类型和数据
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // 启动安装界面
        startActivity(intent);
    }
}
